package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.wemedia.dto.WmLoginDto;
import com.heima.wemedia.entity.WmUser;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-05-19
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser wmUser) {
        //判断参数
        if (wmUser==null || wmUser.getApUserId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否已经存在
        LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
        query.eq(WmUser::getApUserId,wmUser.getApUserId());
        WmUser entity = this.getOne(query);
        if (entity!=null){
            return ResponseResult.okResult(entity);
        }
        this.save(wmUser);
        return ResponseResult.okResult(wmUser);
    }

    @Override
    public ResponseResult login(WmLoginDto dto) {
        //参数判断
        if (dto==null || StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否有这个用户
        LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
        query.eq(WmUser::getName,dto.getName());
        WmUser user = this.getOne(query);
        //如果用户不存在，就返回
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_DATA_NOT_EXIST);
        }
        //如果存在，就校验密码
        String password = dto.getPassword()+user.getSalt();
        String encryptStr = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!encryptStr.equals(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //生成JWT发给客户端
        String token = AppJwtUtil.getToken(user.getId().longValue());
        user.setPassword(null);
        user.setPhone(null);
        user.setSalt(null);
        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
